package com.heima.leetcode.LCR;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class OddEvenPrinter {
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition oddCondition = lock.newCondition();
    private static final Condition evenCondition = lock.newCondition();
    private static int count = 1;
    private static final int MAX = 10;

    public static void main(String[] args) {
        Thread oddThread = new Thread(() -> {
            while (count <= MAX) {
                lock.lock();
                try{
                    if((count & 1) == 1){
                        System.out.println("奇数:" + count++);
                        // evenCondition.signal();
                    }else {
                        oddCondition.await();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread evenThread = new Thread(() -> {
            while (count <= MAX) {
                lock.lock();
                try{
                    if(( count & 1) == 0){
                        System.out.println("偶数:" + count++);
                        // oddCondition.signal();
                    }else {
                        evenCondition.await();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    lock.unlock();
                }
            }
        });

        oddThread.start();
        evenThread.start();
    }
}